<script lang="ts" setup>
import { onMounted, computed, ref, reactive } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import type { FormItemProps, FormInstance, FormProps, FormRules } from 'element-plus'
import { useTagsViewStore } from '@/store/modules/SshtagsView';
const tagsViewStore = useTagsViewStore();
//import { useI18n } from "vue-i18n";
import { useI18n } from '@/hooks/web/useI18n'
import { ResponseData, SshLinkInfoTree, SshSubMenu } from '@/entity/entitys';
import { isValidIPv4, isValidIPv6 } from '@/utils/validate';
import { getSshConnect } from "@/utils/sshUtil";
import { SendSystemNotification } from '@/notification/notification';
const { t } = useI18n();
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  id:0,
  name: '测试1',
  address: '10.10.1.131',
  port: '22',
  username: 'root',
  password: 'root',
  affix: false,
  agreement: 'SSH2',
  favorites_name: '测试1'
});
const validateAddress = (rule: any, value: any, callback: any) => {

  if (ruleForm.address !== '') {
    if (!isValidIPv4(value) && !isValidIPv6(value)) {
      callback(new Error('Please input the correct ip address'))
    }
  }
  callback()

};
const validateFavorites = (rule: any, value: any, callback: any) => {

    if (ruleForm.favorites_name != '') {
      if (value === 'Edit') {
        callback(new Error('不能选择Edit收藏夹'))
      }
    }
    callback()
};
const rules = reactive<FormRules<typeof ruleForm>>({
  address: [{ validator: validateAddress, trigger: 'blur' }, {
    required: true,
    message: 'Please input the ip address',
    trigger: 'blur',
  }],
  username: [
    {
      required: true,
      message: 'Please input the Favorites username',
      trigger: 'blur',
    },
  ],
  name: [
    {
      required: true,
      message: 'Please input the Favorites name',
      trigger: 'blur',
    },
  ],
  favorites_name: [{ validator: validateFavorites, trigger: 'blur' }, {
    required: true,
    message: 'Please input the username',
    trigger: 'blur',
  },],
  password: [{
    required: true,
    message: 'Please input the password',
    trigger: 'blur',
  }]
});


// public id:number=0;
class RestaurantItem {
  value: string
  link: string
  constructor(value: string, link: string) {
    this.value = value;
    this.link = link;
  }
}

const labelPosition = ref<FormProps['labelPosition']>('left')//或者 'top', 'left' 根据需求设定
//const restaurants = ref<RestaurantItem[]>([]);
const querySearch = (queryString: string, cb: any) => {
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value
  // call callback function to return suggestions
  cb(results)
};
const restaurants = computed(() => {
  let arr: RestaurantItem[] = []
  tagsViewStore.getSshLinkInfoTree.forEach((item: SshLinkInfoTree) => {
    arr.push(new RestaurantItem(item.favorites_name, item.favorites_name))
  })
  return arr;
})

const createFilter = (queryString: string) => {
  return (restaurant: RestaurantItem) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    )
  }
}


const handleSelect = (item: RestaurantItem) => {
  console.log(item)
}

onMounted(() => {
  //restaurants.value = loadAll;
})
const onSubmit = () => {
  console.log('submit!', ruleForm)
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!',ruleForm)
      invoke('connection_create', {map:ruleForm}).then((res): void => {
        let res_data=res as ResponseData<string>
        if (res_data.code == 200) {
          getSshConnect();
        }
        SendSystemNotification(t('appName'), res_data.msg)
    })
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
<template>
  <div class="connectAdd">
    <el-form :rules="rules" ref="ruleFormRef" :label-position="labelPosition" :model="ruleForm" label-width="auto"
      style="max-width: 600px">
      <el-form-item :label="$t('connectAdd.favorites_name')" prop="favorites_name">
        <el-autocomplete v-model="ruleForm.favorites_name" :fetch-suggestions="querySearch" clearable
          :placeholder="$t('PleaseInput')" @select="handleSelect" />
      </el-form-item>
      <el-form-item :label="$t('connectAdd.connectName')" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>
      <el-form-item :label="$t('connectAdd.connectAddress')" prop="address">
        <el-input v-model="ruleForm.address" />
      </el-form-item>
      <el-form-item :label="$t('connectAdd.connectPort')" prop="port">
        <el-input-number :min="1" v-model="ruleForm.port" />
      </el-form-item>
      <el-form-item :label="$t('connectAdd.connectUsername')" prop="username">
        <el-input v-model="ruleForm.username" />
      </el-form-item>
      <el-form-item :label="$t('connectAdd.connectPassword')" prop="password">
        <el-input v-model="ruleForm.password" type="password" show-password />
      </el-form-item>

      <el-form-item :label="$t('connectAdd.connectAffix')" prop="affix">
        <el-switch v-model="ruleForm.affix" />
      </el-form-item>
      <el-form-item :label="$t('connectAdd.connectAgreement')" prop="agreement">
        <el-radio-group v-model="ruleForm.agreement">
          <el-radio value="SSH1" name="type">
            SSH1
          </el-radio>
          <el-radio value="SSH2" name="type">
            SSH2
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button @click="submitForm(ruleFormRef)">{{ t('action.create') }}</el-button>
        <el-button @click="resetForm(ruleFormRef)">{{ t('common.clear') }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style lang="scss" scoped>
.connectAdd {
  padding: 10px 20px;
}
</style>